package com.weimob.mcloud.wechatwork.customer.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.weimob.artemis.client.consumer.model.ConsumerRecord;
import com.weimob.artemis.client.consumer.model.MessageResult;
import com.weimob.artemis.client.spring.annotation.ArtemisConsumerListener;
import com.weimob.artemis.client.spring.annotation.Subscribe;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.base.BaseAuthReqDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.request.CustomerSearchDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.response.CustomerSearchBO;
import com.weimob.mcloud.wechatwork.core.adapter.service.OneCrmAdapterService;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.base.SingleRequest;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.tag.MarkTagDetail;
import com.weimob.mcloud.wechatwork.core.entity.relation.tag.MarkTagTask;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.tag.MarkTagDetailStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.tag.MarkTagTaskStatusEnum;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.core.service.tag.TagTaskCoreService;
import com.weimob.mcloud.wechatwork.customer.convertor.customer.CustomerConvert;
import com.weimob.mcloud.wechatwork.customer.convertor.customer.CustomerRequestBuild;
import com.weimob.mcloud.wechatwork.customer.convertor.tag.TagConvert;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisBaseInfo;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
import com.weimob.mcloud.wechatwork.customer.facade.impl.customer.CustomerFacade;
import com.weimob.mcloud.wechatwork.customer.service.TagManageService;
import com.weimob.mcloud.wechatwork.customer.service.impl.ArtemisService;
import com.weimob.mcloud.wechatwork.customer.service.user.base.PrivateSphereDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.MarkTagSourceEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.TagOperateTypeEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BizException;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.customer.ExternalUserListBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.tag.TagGroupBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.customer.ExternalUserInfoFindDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.tag.CustomerTagDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.tag.TagDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.tag.v2.CdpTagGroupItemDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.tag.v2.MarkTagTaskMessage;
import com.weimob.mcloud.wechatwork.customer.third.tag.CdpTagThird;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import com.weimob.zipkin.ZipkinContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author junlong.lv
 * @version 1.0
 * @date 2022/8/5 7:03 上午
 */
@Component
@Slf4j
public class MarkTagTaskConsumer {

    @Reference
    private PrivateSphereService privateSphereService;

    @Reference
    private TagTaskCoreService tagTaskCoreService;

    @Reference
    private OneCrmAdapterService oneCrmAdapterService;

    @Autowired
    private CustomerFacade customerFacade;

    @Autowired
    private ArtemisService artemisService;

    @Autowired
    private TagManageService tagManageService;

    @Autowired
    private CdpTagThird cdpTagThird;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;

    @Value("${query.wid.page.size:100}")
    private Integer queryWidPageSize;

    @Value("${batch.insert.wid.size:50}")
    private Integer batchInsertWidSize;

    @ArtemisConsumerListener(value = @Subscribe(topic = ArtemisConstant.Topic.WECHATWORK_BATCH_MARK_TAG_TASK_INIT_TOPIC,
            user = ArtemisConstant.CONSUMER_USER), interval = 50)
    public void markTagTaskInit(MessageResult result) {

        // 1.从消息里拿出要同步的外部联系人数据
        List<ConsumerRecord> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return;
        }

        for (ConsumerRecord consumerRecord : records) {


            log.info("批量打标任务初始化, message:{}", consumerRecord.getValue());
            MarkTagTaskMessage markTagTaskMessage = JSON.parseObject(consumerRecord.getValue(), MarkTagTaskMessage.class);

            if (null == markTagTaskMessage) {
                log.error("打标任务初始化失败, 参数不允许为空");
                continue;
            }


            Long bosId = markTagTaskMessage.getBosId();
            Long taskId = markTagTaskMessage.getTaskId();
            Long bwid = markTagTaskMessage.getBwid();
            if (null == bosId || null == taskId || null == bwid) {
                log.error("打标任务初始化失败, 参数不合法, param:{}", markTagTaskMessage);
                continue;
            }

            PrivateSphere queryPrivateSphere = new PrivateSphere();
            queryPrivateSphere.setBosId(markTagTaskMessage.getBosId());
            queryPrivateSphere.setProductId(aewcProductId);

            SoaResponse<PrivateSphere, Void> fetch = privateSphereService.simpleFetch(queryPrivateSphere);
            if (0L != Long.parseLong(fetch.getReturnCode()) || null == fetch.getResponseVo()) {
                log.error("初始化打标任务失败, 查询私域失败, request:{}, response:{}", JSON.toJSONString(queryPrivateSphere), JSON.toJSONString(fetch));
                continue;
            }


            try {
                //初始化任务执行
                markTagTagTaskInit(markTagTaskMessage, fetch.getResponseVo());
            } catch (Exception e) {

                //处理异常情况
                log.error("初始化打标任务失败, record:{}, error:{}", consumerRecord, e);


                //更新任务状态, 初始化失败
                PrivateSphere privateSphere = fetch.getResponseVo();
                SingleRequest<MarkTagTask> initFinishRequest = new SingleRequest<>();
                MarkTagTask updateInitFinish = new MarkTagTask();
                updateInitFinish.setTaskId(markTagTaskMessage.getTaskId());
                updateInitFinish.setPrivateSphereId(privateSphere.getPrivateSphereId());
                updateInitFinish.setBwid(markTagTaskMessage.getBwid());
                updateInitFinish.setStatus(MarkTagTaskStatusEnum.INIT_TASK_FAIL.getStatus());
                initFinishRequest.setData(updateInitFinish);

                SoaResponse<Boolean, Void> initFinishSoaResponse = tagTaskCoreService.updateMarkTagTask(initFinishRequest);
                if (0L != Long.parseLong(initFinishSoaResponse.getReturnCode())) {
                    log.error("初始化打标任务失败, 更新任务状态为初始化任务成功失败, request:{}, response:{}",
                            JSON.toJSONString(initFinishRequest), JSON.toJSONString(initFinishSoaResponse));
                }
            }
        }
    }

    public void markTagTagTaskInit(MarkTagTaskMessage markTagTaskMessage, PrivateSphere privateSphere) {

        Long taskId = markTagTaskMessage.getTaskId();
        Long bwid = markTagTaskMessage.getBwid();


        //查询任务
        SingleRequest<MarkTagTask> request = new SingleRequest<>();
        MarkTagTask markTagTask = new MarkTagTask();
        markTagTask.setPrivateSphereId(privateSphere.getPrivateSphereId());
        markTagTask.setTaskId(taskId);
        markTagTask.setBwid(bwid);
        request.setData(markTagTask);
        SoaResponse<MarkTagTask, Void> markTagTaskVoidSoaResponse = tagTaskCoreService.queryMarkTagTask(request);
        if (0L != Long.parseLong(markTagTaskVoidSoaResponse.getReturnCode())) {
            log.error("初始化打标任务失败, request:{}, response:{}", JSON.toJSONString(request), JSON.toJSONString(markTagTaskVoidSoaResponse));
            return;
        }

        MarkTagTask markTagTaskTResponse = markTagTaskVoidSoaResponse.getResponseVo();
        if (null == markTagTaskTResponse) {
            log.error("初始化打标任务失败, 未查询到该任务");
            return;
        }

        if (!markTagTaskTResponse.getStatus().equals(MarkTagTaskStatusEnum.CREATE_TASK.getStatus())) {
            log.error("初始化打标任务失败, 该批次任务状态不合法, response:{}", JSON.toJSONString(markTagTaskTResponse));
            return;
        }

        //更新任务状态, 将未初始化状态更新为进行中
        SingleRequest<MarkTagTask> updateMarkTagTask = new SingleRequest<>();
        MarkTagTask update = new MarkTagTask();
        update.setTaskId(taskId);
        update.setPrivateSphereId(privateSphere.getPrivateSphereId());
        update.setBwid(bwid);
        update.setStatus(MarkTagTaskStatusEnum.INIT_TASK.getStatus());
        updateMarkTagTask.setData(update);

        SoaResponse<Boolean, Void> booleanVoidSoaResponse = tagTaskCoreService.updateMarkTagTask(updateMarkTagTask);
        if (0L != Long.parseLong(booleanVoidSoaResponse.getReturnCode())) {
            log.error("初始化打标任务失败, 更新任务状态为进行中失败, request:{}, response:{}",
                    JSON.toJSONString(updateMarkTagTask), JSON.toJSONString(booleanVoidSoaResponse));
            return;
        }

        //根据查询条件查人
        ExternalUserInfoFindDTO externalUserInfoFindDTO = JSONObject.parseObject(markTagTaskTResponse.getQuery(),
                ExternalUserInfoFindDTO.class);
        if (null == externalUserInfoFindDTO) {
            log.error("获取查询条件为空, 任务批次参数:{}", JSON.toJSONString(markTagTaskMessage));
            return;
        }

        externalUserInfoFindDTO.setStatus(CustomerStatusEnum.DEFAULT.getCode());
        List<CdpTagGroupItemDTO> tagList = externalUserInfoFindDTO.getTagList();


        List<Long> assignWidList = externalUserInfoFindDTO.getAssignWidList();
        if (CollectionUtils.isNotEmpty(assignWidList)) {

            List<ExternalUserListBO> externalUserListBOS = customerFacade.getExternalUserInfoByWids(privateSphere, assignWidList, null, false);
            if (CollectionUtils.isNotEmpty(externalUserListBOS)) {

                //初始化任务
                Set<String> customerIdSet = CustomerConvert.toCustomerIds(externalUserListBOS);
                init(Lists.newArrayList(customerIdSet), privateSphere, markTagTaskMessage, tagList);
            }

        } else {

            externalUserInfoFindDTO.setPageNum(1);
            externalUserInfoFindDTO.setPageSize(queryWidPageSize);
            BaseAuthReqDTO<CustomerSearchDTO> baseAuthReqDTO = new BaseAuthReqDTO<>();
            CustomerSearchBO customerSearchBO;

            customerFacade.handlerAuthorizeVidList(privateSphere, externalUserInfoFindDTO);


            do {

                CustomerSearchDTO customerSearchDTO = CustomerRequestBuild.buildOneCrmSearchRequest(privateSphere.getCorpId(), externalUserInfoFindDTO);
                customerSearchDTO.setCursor(externalUserInfoFindDTO.getCursor());
                baseAuthReqDTO.setRequest(customerSearchDTO);
                //客户搜索
                customerSearchBO = SoaUtil.unpack(oneCrmAdapterService.searchUserInfoByScroll(customerSearchDTO));
                log.info("初始化批量打标任务, queryExternalUserBaseInfoList, request:{}, result:{}, ticket:{}", JSON.toJSONString(baseAuthReqDTO), JSON.toJSONString(customerSearchBO),
                        ZipkinContext.getContext().getGlobalTicket());

                if (CollectionUtils.isEmpty(customerSearchBO.getWids())) {
                    break;
                }

                List<Long> wids = customerSearchBO.getWids();

                //过滤指定wid
                List<Long> removeWidList = externalUserInfoFindDTO.getRemoveWidList();
                if (CollectionUtils.isNotEmpty(removeWidList)) {
                    wids = filter(customerSearchBO.getWids(), removeWidList);
                }



                if (CollectionUtils.isNotEmpty(wids)) {
                    List<ExternalUserListBO> externalUserListBOS = customerFacade.getExternalUserInfoByWids(privateSphere, wids, null, false);


                    if (CollectionUtils.isNotEmpty(externalUserListBOS)) {

                        //初始化任务
                        Set<String> customerIdSet = CustomerConvert.toCustomerIds(externalUserListBOS);
                        init(Lists.newArrayList(customerIdSet), privateSphere, markTagTaskMessage, tagList);

                    }
                }

                //查询所有用户
                externalUserInfoFindDTO.setCursor(customerSearchBO.getCursor());
                externalUserInfoFindDTO.setPageNum(externalUserInfoFindDTO.getPageNum() + 1);
            } while (customerSearchBO.getWids() != null && externalUserInfoFindDTO.getPageSize().equals(customerSearchBO.getWids().size()));

        }


        //更新任务状态, 初始化完成
        SingleRequest<MarkTagTask> initFinishRequest = new SingleRequest<>();
        MarkTagTask updateInitFinish = new MarkTagTask();
        updateInitFinish.setTaskId(taskId);
        updateInitFinish.setPrivateSphereId(privateSphere.getPrivateSphereId());
        updateInitFinish.setBwid(bwid);
        updateInitFinish.setStatus(MarkTagTaskStatusEnum.INIT_TASK_SUCCESS.getStatus());
        initFinishRequest.setData(updateInitFinish);

        SoaResponse<Boolean, Void> initFinishSoaResponse = tagTaskCoreService.updateMarkTagTask(initFinishRequest);
        if (0L != Long.parseLong(initFinishSoaResponse.getReturnCode())) {
            log.error("初始化打标任务失败, 更新任务状态为初始化任务成功失败, request:{}, response:{}",
                    JSON.toJSONString(initFinishRequest), JSON.toJSONString(initFinishSoaResponse));
            return;
        }

        //发送初始化任务完成消息，通知打标
        MarkTagTaskMessage markTagTaskInitFinish = new MarkTagTaskMessage();
        markTagTaskInitFinish.setTaskId(markTagTaskMessage.getTaskId());
        markTagTaskInitFinish.setBosId(privateSphere.getBosId());
        markTagTaskInitFinish.setBwid(markTagTaskMessage.getBwid());
        markTagTaskInitFinish.setOperateType(markTagTaskMessage.getOperateType());

        ArtemisBaseInfo<MarkTagTaskMessage> artemisBaseInfo = new ArtemisBaseInfo<>();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.WECHATWORK_BATCH_MARK_TASG__TASK_START);
        artemisBaseInfo.setEvent(markTagTaskInitFinish);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        log.info("批量打标任务开启, magBody:{}", JSON.toJSONString(artemisBaseInfo));
        artemisService.sendToArtemis(artemisBaseInfo, privateSphere.getBosId());

    }

    private List<Long> filter(List<Long> target, List<Long> remove) {
        if (CollectionUtils.isEmpty(remove)) {
            return new ArrayList<>();
        }

        if (CollectionUtils.isEmpty(target)) {
            return new ArrayList<>();
        }

        List<Long> filter = new ArrayList<>();
        for (Long wid : target) {
            if (remove.contains(wid)) {
                continue;
            }

            filter.add(wid);
        }

        return filter;
    }

    /**
     * 开始打标
     *
     * @param result
     */
    @ArtemisConsumerListener(value = @Subscribe(topic = ArtemisConstant.Topic.WECHATWORK_BATCH_MARK_TASG__TASK_START,
            user = ArtemisConstant.CONSUMER_USER), interval = 50)
    public void markTagRunning(MessageResult result) {
        List<ConsumerRecord> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return;
        }

        for (ConsumerRecord consumerRecord : records) {
            try {
                log.info("批量打标任务开始执行, message:{}", consumerRecord.getValue());
                
                MarkTagTaskMessage markTagTaskMessage = JSON.parseObject(consumerRecord.getValue(), MarkTagTaskMessage.class);
                markTagHandle(markTagTaskMessage);

            } catch (Exception e) {
                log.error("打标任务执行失败, record:{}, error:{}", consumerRecord, e);
            }
        }
    }

    public void markTagHandle(MarkTagTaskMessage markTagTaskMessage) {
        if (null == markTagTaskMessage) {
            log.error("打标任务初始化失败, 参数不允许为空");
            return;
        }

        Long bosId = markTagTaskMessage.getBosId();
        Long taskId = markTagTaskMessage.getTaskId();
        Long bwid = markTagTaskMessage.getBwid();
        if (null == bosId || null == taskId || null == bwid) {
            log.error("打标任务初始化失败, 参数不合法, param:{}", markTagTaskMessage);
            return;
        }


        PrivateSphere queryPrivateSphere = new PrivateSphere();
        queryPrivateSphere.setBosId(bosId);
        queryPrivateSphere.setProductId(aewcProductId);

        SoaResponse<PrivateSphere, Void> fetch = privateSphereService.fetch(queryPrivateSphere);
        if (0L != Long.parseLong(fetch.getReturnCode()) || null == fetch.getResponseVo()) {
            log.error("初始化打标任务失败, 查询私域失败, request:{}, response:{}", JSON.toJSONString(queryPrivateSphere), JSON.toJSONString(fetch));
            return;
        }

        PrivateSphere privateSphere = fetch.getResponseVo();

        //查询任务
        SingleRequest<MarkTagTask> request = new SingleRequest<>();
        MarkTagTask markTagTask = new MarkTagTask();
        markTagTask.setPrivateSphereId(privateSphere.getPrivateSphereId());
        markTagTask.setTaskId(taskId);
        markTagTask.setBwid(bwid);
        request.setData(markTagTask);
        SoaResponse<MarkTagTask, Void> markTagTaskVoidSoaResponse = tagTaskCoreService.queryMarkTagTask(request);
        if (0L != Long.parseLong(markTagTaskVoidSoaResponse.getReturnCode())) {
            log.error("执行打标任务失败, 查询任务失败, request:{}, response:{}", JSON.toJSONString(request), JSON.toJSONString(markTagTaskVoidSoaResponse));
            return;
        }

        MarkTagTask markTagTaskTResponse = markTagTaskVoidSoaResponse.getResponseVo();
        if (null == markTagTaskTResponse) {
            log.error("执行打标任务失败, 未查询到该任务, request:{}", JSON.toJSONString(request));
            return;
        }

        if (!markTagTaskTResponse.getStatus().equals(MarkTagTaskStatusEnum.INIT_TASK_SUCCESS.getStatus())) {
            log.warn("任务状态不合法，无需进行打标, param:{}", markTagTaskMessage);
            return;
        }


        // 1.初始化取数据的ID位置为0
        Long nextId = 0L;
        SingleRequest<MarkTagTask> queryDetailRequest = new SingleRequest<>();
        MarkTagTask markTagTaskQuery = new MarkTagTask();
        markTagTaskQuery.setPrivateSphereId(privateSphere.getPrivateSphereId());
        markTagTaskQuery.setBwid(bwid);
        markTagTaskQuery.setTaskId(taskId);


        // 2.初始化 客户-员工关系 list
        List<MarkTagDetail> markTagDetailList = null;
        do {

            markTagTaskQuery.setNextId(nextId);
            markTagTaskQuery.setDetailStatus(MarkTagDetailStatusEnum.INIT_TASK_SUCCESS.getStatus());

            queryDetailRequest.setData(markTagTaskQuery);
            queryDetailRequest.setNeedPage(true);
            queryDetailRequest.setPageNum(1);
            queryDetailRequest.setPageSize(100);

            log.info("打标任务进行中, 查询任务详情信息, request:{}", JSON.toJSONString(queryDetailRequest));
            SoaResponse<MultiResponse<MarkTagDetail>, Void> multiResponseVoidSoaResponse = tagTaskCoreService.
                    queryMarkTagDetail(queryDetailRequest);
            log.info("打标任务进行中, 查询任务详情信息, 返回结果, request:{}, response:{}",
                    JSON.toJSONString(queryDetailRequest), JSON.toJSONString(multiResponseVoidSoaResponse));

            if (0L != Long.parseLong(multiResponseVoidSoaResponse.getReturnCode())) {
                log.error("查询打标任务详情失败, request:{}, response:{}", JSON.toJSONString(queryDetailRequest), JSON.toJSONString(multiResponseVoidSoaResponse));
                break;
            }

            MultiResponse<MarkTagDetail> multiResponse = multiResponseVoidSoaResponse.getResponseVo();
            if (null == multiResponse || CollectionUtils.isEmpty(multiResponse.getDataList())) {
                break;
            }

            markTagDetailList = multiResponse.getDataList();

            //打标
            log.info("测试使用前, request:{}", JSON.toJSONString(markTagDetailList));
            markTag(privateSphere, markTagDetailList);
            log.info("测试使用后, request:{}", JSON.toJSONString(markTagDetailList));

            // X.更新nextId的位置
            nextId = markTagDetailList.get(markTagDetailList.size() - 1).getId();

//            queryDetailRequest.setPageNum(queryDetailRequest.getPageNum() + 1);


        }
        while (CollectionUtils.isNotEmpty(markTagDetailList));

        log.info("打标完成, 更新任务状态, request:{}", JSON.toJSONString(markTagTaskMessage));

        //更新任务状态, 将未初始化状态更新为打标完成
        SingleRequest<MarkTagTask> updateMarkTagTask = new SingleRequest<>();
        MarkTagTask update = new MarkTagTask();
        update.setTaskId(taskId);
        update.setPrivateSphereId(privateSphere.getPrivateSphereId());
        update.setBwid(bwid);
        update.setStatus(MarkTagTaskStatusEnum.TASK_EXECUTE_SUCCESS.getStatus());
        updateMarkTagTask.setData(update);

        SoaResponse<Boolean, Void> booleanVoidSoaResponse = tagTaskCoreService.updateMarkTagTask(updateMarkTagTask);
        if (0L != Long.parseLong(booleanVoidSoaResponse.getReturnCode())) {
            log.error("更新打标任务状态失败, 更新任务状态为打标完成失败, request:{}, response:{}",
                    JSON.toJSONString(updateMarkTagTask), JSON.toJSONString(booleanVoidSoaResponse));
        }

    }

    private void markTag(PrivateSphere privateSphere, List<MarkTagDetail> markTagDetails) {

        if (CollectionUtils.isEmpty(markTagDetails)) {
            return;
        }


        //每批任务所打的标签数据都是一样的
        String cdpTagList = markTagDetails.get(0).getTagList();

        // 查询标签，校验标签是否存在
        List<TagGroupBO> tagGroupBOList = null;
        try {

            List<CdpTagGroupItemDTO> cdpTagItemList = JSONObject.parseArray(cdpTagList, CdpTagGroupItemDTO.class);
            Map<String, Set<String>> cdpTagGroupIdMap = TagConvert.toCdpGroupIdAndCdpTagIdsMap(cdpTagItemList);
            tagGroupBOList = cdpTagThird.queryTagByCdpTagIds(privateSphere.getBosId(), cdpTagGroupIdMap);

        } catch (Exception e) {
            log.error("批量打标签任务失败, bosId:{}, tagRequest:{}, error:{}", privateSphere.getBosId(),
                    cdpTagList, JSON.toJSONString(tagGroupBOList));

            tagGroupBOList = new ArrayList<>();
        }


        for (MarkTagDetail markTagDetail : markTagDetails) {

            try {

                if (CollectionUtils.isEmpty(tagGroupBOList)) {
                    throw new BizException("标签数据不存在");
                }

                CustomerTagDTO customerTagDTO = new CustomerTagDTO();
                customerTagDTO.setCustomerId(markTagDetail.getCustomerId());

                PrivateSphereDTO privateSphereDTO = new PrivateSphereDTO();
                privateSphereDTO.setBosId(privateSphere.getBosId());
                privateSphereDTO.setPrivateSphereId(privateSphere.getPrivateSphereId());
                privateSphereDTO.setProductInstanceId(privateSphere.getProductInstanceId());
                privateSphereDTO.setCorpId(privateSphere.getCorpId());

                customerTagDTO.setPrivateSphereDTO(privateSphereDTO);
                customerTagDTO.setOperateType(markTagDetail.getOperateType());
                customerTagDTO.setMarkSource(MarkTagSourceEnum.OUTTER.getSource());
                customerTagDTO.setOffline(true);

                String tagList = markTagDetail.getTagList();
                List<CdpTagGroupItemDTO> tagLis = JSONObject.parseArray(tagList, CdpTagGroupItemDTO.class);

                List<TagDTO> tagDTOList = TagConvert.toTagDTOList(tagLis);
                customerTagDTO.setTagDTOList(tagDTOList);

                SoaResponse<Boolean, ?> markTagSoa = null;
                if (markTagDetail.getOperateType().equals(TagOperateTypeEnum.ADD.getCode())) {
                    markTagSoa = tagManageService.addCustomerTag(customerTagDTO);
                } else {
                    markTagSoa = tagManageService.removeCustomerTag(customerTagDTO, true);
                }


                SingleRequest<MarkTagDetail> updateRequest = new SingleRequest<>();
                MarkTagDetail updateMarkTagDetail = new MarkTagDetail();
                updateMarkTagDetail.setPrivateSphereId(privateSphere.getPrivateSphereId());
                updateMarkTagDetail.setTaskId(markTagDetail.getTaskId());
                updateMarkTagDetail.setBwid(markTagDetail.getBwid());
                updateMarkTagDetail.setId(markTagDetail.getId());

                if (0L == Long.parseLong(markTagSoa.getReturnCode())) {
                    updateMarkTagDetail.setStatus(MarkTagDetailStatusEnum.MARK_TAG_SUCCESS.getStatus());
                } else {
                    updateMarkTagDetail.setStatus(MarkTagDetailStatusEnum.MARK_TAG_FAIL.getStatus());
                    updateMarkTagDetail.setMessage(markTagSoa.getReturnMsg());
                }

                updateRequest.setData(updateMarkTagDetail);
                tagTaskCoreService.updateMarkTagDetail(updateRequest);

            } catch (Exception e) {
                log.error("批量打标任务失败, markTagDetail:{}, error:{}", JSON.toJSONString(markTagDetail), e);


                SingleRequest<MarkTagDetail> updateRequest = new SingleRequest<>();
                MarkTagDetail updateMarkTagDetail = new MarkTagDetail();
                updateMarkTagDetail.setPrivateSphereId(privateSphere.getPrivateSphereId());
                updateMarkTagDetail.setTaskId(markTagDetail.getTaskId());
                updateMarkTagDetail.setBwid(markTagDetail.getBwid());
                updateMarkTagDetail.setId(markTagDetail.getId());

                updateMarkTagDetail.setStatus(MarkTagDetailStatusEnum.MARK_TAG_FAIL.getStatus());
                updateMarkTagDetail.setMessage(e.getMessage());
                updateRequest.setData(updateMarkTagDetail);
                tagTaskCoreService.updateMarkTagDetail(updateRequest);
            }
        }
    }


    private void init(List<String> customerIds, PrivateSphere privateSphere, MarkTagTaskMessage markTagTaskMessage, List<CdpTagGroupItemDTO> tagList) {

        List<List<String>> partition = Lists.partition(customerIds, batchInsertWidSize);

        for (List<String> partitionCustomerIds : partition) {

            SingleRequest<List<MarkTagDetail>> batchInsertRequest = new SingleRequest<>();
            List<MarkTagDetail> markTagDetailList = new ArrayList<>();
            for (String customerId : partitionCustomerIds) {
                MarkTagDetail markTagDetail = new MarkTagDetail();
                markTagDetail.setPrivateSphereId(privateSphere.getPrivateSphereId());
                markTagDetail.setTaskId(markTagTaskMessage.getTaskId());
                markTagDetail.setBwid(markTagTaskMessage.getBwid());
                markTagDetail.setStatus(MarkTagDetailStatusEnum.INIT_TASK_SUCCESS.getStatus());
                markTagDetail.setOperateType(markTagTaskMessage.getOperateType());
                markTagDetail.setCustomerId(customerId);
                markTagDetail.setDeleted(false);
                markTagDetail.setCreateTime(new Date());
                markTagDetail.setUpdateTime(new Date());
                markTagDetail.setTagList(JSON.toJSONString(tagList));

                markTagDetailList.add(markTagDetail);
            }

            batchInsertRequest.setData(markTagDetailList);
            SoaResponse<Boolean, Void> booleanVoidSoaResponse1 = tagTaskCoreService.batchInsert(batchInsertRequest);
        }
    }
}
